'use strict'

const fs = require('fs')
const path = require('path')

//生成验证图片的第三方包
const captchapng = require('captchapng')

//获取登录页面
exports.getLoginPage = (req,res)=>{
    //读取我们的login.html,并且返回给浏览器呈现
    fs.readFile(path.join(__dirname,'../views/login.html'),(err,data)=>{
      res.setHeader('Content-Type','text/html;charset=utf8')
      res.end(data)
    })
}

//获取验证码图片的逻辑
exports.getVcodeImage = (req,res)=>{
  /**
   * 最终返回带有数字的图片
   */
  
  const vcode = parseInt(Math.random()*9000+1000)

  //利用我们刚刚开辟的内存空间，存储我们的验证码数字
  req.session.vcode = vcode
  
  var p = new captchapng(80,30,vcode); // width,height,numeric captcha 
  p.color(0, 0, 0, 0);  // First color: background (red, green, blue, alpha) 
  p.color(80, 80, 80, 255); // Second color: paint (red, green, blue, alpha) 

  var img = p.getBase64();
  var imgbase64 = new Buffer(img,'base64');
  //res.setHeader()
  res.writeHead(200, {
      'Content-Type': 'image/png'
  });
  res.end(imgbase64);
}

//处理登录请求
exports.login = (req,res)=>{
  
  //1.获取浏览器传递过来的验证码
  const vcode1 = parseInt(req.body.vcode || '')

  //2.获取存储在session中的vcode
  const vcode2 = req.session.vcode

  //设定成功之后的结果
  const result = {status:0,message:'登录成功'}

  //校验了验证码
  if (vcode1 != vcode2) {
    result.status = 1
    result.message = '验证码错误'
  }

  //返回结果
  res.json(result)
}
